package com.xzlf.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object>redisTemplate(@Qualifier("redissonConnectionFactory") RedisConnectionFactory factory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        return redisTemplate;
    }

    @Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://aliyun.esc:6380")
                .setRetryInterval(100)
                .setPassword("oldlin11??");

        //集群模式,集群节点的地址须使用“redis://”前缀，否则将会报错。
        //此例集群为3节点，各节点1主1从
//        config.useClusterServers()
//                .addNodeAddress("redis://192.168.80.101:7001","redis://192.168.80.101:7002",
//                "redis://192.168.80.101:7003","redis://192.168.80.101:7004","redis://192.168.80.101:7005",
//                "redis://192.168.80.101:7006");
//        config.useClusterServers().addNodeAddress("redis://aliyun.esc:7001","redis://aliyun.esc:7002",
//                "redis://aliyun.esc:7003","redis://aliyun.esc:7004","redis://aliyun.esc:7005","redis://aliyun.esc:7006");
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }
}
